import router, { notFoundRoute } from '@/router'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import { useUserStore } from './user'

export const usePermissionStore = defineStore('permission', () => {
  const accessedRoutes = ref<RouteRecordRaw[]>([])
  const isRoutesGenerated = ref(false)

  /**
   * 生成路由
   */
  const generateRoutes = async (): Promise<RouteRecordRaw[]> => {
    const userStore = useUserStore()
    const menuList = userStore.menuList
    if (!menuList || menuList.length === 0) {
      accessedRoutes.value = []
      isRoutesGenerated.value = false
      return []
    }

    // 转换菜单为路由
    const routes = convertMenuToRoutes(menuList)
    accessedRoutes.value = routes
    isRoutesGenerated.value = true
    // 动态添加路由，作为Layout组件的子路由
    routes.forEach((route) => {
      router.addRoute('Layout', route)
    })

    // 在所有动态路由添加完成后，添加通配符路由作为最后的匹配规则
    router.addRoute(notFoundRoute)
    return routes
  }

  /**
   * 清除路由
   */
  const clearRoutes = () => {
    accessedRoutes.value = []
    isRoutesGenerated.value = false
  }

  return {
    accessedRoutes,
    isRoutesGenerated,
    generateRoutes,
    clearRoutes
  }
})

/**
 * 将菜单数据转换为路由配置
 */
function convertMenuToRoutes(menuList: any[]): RouteRecordRaw[] {
  const modules = import.meta.glob('@/views/**/*.vue')

  const buildRoutes = (menus: ResourceInfo[], parentId: number | null = null): RouteRecordRaw[] => {
    return menus
      .filter((menu) => {
        // 处理顶级菜单：当parentId为null时匹配parentId为0或null的菜单
        if (parentId === null) {
          return menu.parentId === 0 || menu.parentId === null
        }
        return menu.parentId === parentId
      })
      .sort((a, b) => (a.sort || 0) - (b.sort || 0))
      .map((menu) => {
        const route: RouteRecordRaw = {
          path: menu.path || `/${menu.code}`,
          name: menu.code,
          redirect: menu.redirect,
          meta: {
            id: menu.id,
            title: menu.name,
            icon: menu.icon,
            isCache: menu.isCache || false,
            isHidden: menu.isHidden || false
          }
        }
        // 设置组件
        if (menu.component) {
          // 使用动态导入获取组件
          const componentPath = `/src/views/${menu.component}.vue`
          if (modules[componentPath]) {
            route.component = modules[componentPath] as any
          } else {
            // 降级处理，直接导入
            route.component = (() => import(`@/views/${menu.component}.vue`)) as any
          }
        }

        // 递归处理子路由
        const children = buildRoutes(menu.children || [], menu.id)
        if (children.length > 0) {
          route.children = children
          // 如果有子路由，设置重定向到第一个子路由
          route.redirect = children[0].path
        }

        return route
      })
  }

  return buildRoutes(menuList)
}
